package tree;

/**
 * Created with IntelliJ IDEA.
 * Description: 236. 二叉树的最近公共祖先
 * User: Li_yizYa
 * Date: 2025/6/9
 * Time: 20:28
 */
public class Solution31 {
    /**
     * 递归实现
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == p || root == q || root == null) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null && right == null) {
            return null;
        } else if (left != null && right == null) {
            return left;
        } else if (left == null && right != null) {
            return right;
        } else {
            return root;
        }
    }
}
